package com.quasar.hpatient.view.record;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.quasar.hpatient.MainAppliaction;
import com.quasar.hpatient.R;
import com.quasar.hpatient.base.BaseActivity;
import com.quasar.hpatient.constant.ConstantManger;
import com.quasar.hpatient.model.custommodel.TemperatureTableItem;
import com.quasar.hpatient.model.httpmodel.AnotherResult;
import com.quasar.hpatient.model.httpmodel.DataStateResult;
import com.quasar.hpatient.model.medicalmodel.DailyRecordDetailsData;
import com.quasar.hpatient.onInterface.OndailyRecordListener;
import com.quasar.hpatient.presenter.DailyRecordPresenter;
import com.quasar.hpatient.utils.OutliersValues;
import com.quasar.hpatient.utils.StringUtils;
import com.quasar.hpatient.utils.TimeZoneUtil;
import com.quasar.hpatient.view.adapter.BloodSugarAdapter;
import com.quasar.hpatient.widget.SeekBarEditWidget;
import com.quasar.hpatient.widget.WidgetDateAdd;
import com.quasar.hpatient.widget.WidgetTime;
import com.quasar.hpatient.widget.lineChartView;
import com.rey.material.app.Dialog;
import com.rey.material.app.DialogFragment;
import com.rey.material.app.SimpleDialog;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.OptionsItem;
import org.androidannotations.annotations.OptionsMenu;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringArrayRes;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 血糖
 */
@OptionsMenu(R.menu.menu_preservation)
@EActivity(R.layout.activity_blood_sugar)
public class BloodSugarActivity extends BaseActivity implements OndailyRecordListener {

    private BloodSugarAdapter bloodSugarAdapter;
    private DailyRecordPresenter dailyRecordPresenter;

    @StringArrayRes
    String[] choose_blood_sugar;
    @StringArrayRes
    String[] choose_blood_time;
    @ViewById(R.id.main_toolbar)
    Toolbar main_toolbar;
    //选择记录类型
    @ViewById(R.id.id_flowlayout)
    TagFlowLayout id_flowlayout;

    @ViewById(R.id.rv_list)
    RecyclerView rv_list;
    @ViewById(R.id.lc_post_list)
    lineChartView lc_post_list;
    @ViewById(R.id.wd_dataAdd)
    WidgetDateAdd wd_dataAdd;
    //检测值
    @ViewById(R.id.sw_testingVal)
    SeekBarEditWidget sw_testingVal;
    int When = -1;
    @ViewById(R.id.wt_time)
    WidgetTime wt_time;
    @Extra
    String TimeVal;//其他跳转过来的时间

    @AfterViews
    void init() {
        initView();
        initData();
    }

    @Override
    protected void initView() {
        initToolbar();

        rv_list.setLayoutManager(new LinearLayoutManager(this));
        rv_list.setHasFixedSize(true);
        rv_list.setNestedScrollingEnabled(false);

        //单选
        final LayoutInflater mInflater = LayoutInflater.from(this);
        TagAdapter tagAdapter = new TagAdapter<String>(choose_blood_sugar) {
            @Override
            public View getView(FlowLayout parent, int position, String s) {
                TextView tv = (TextView) mInflater.inflate(R.layout.tv,
                        id_flowlayout, false);
                tv.setText(s);
                return tv;
            }
        };

        id_flowlayout.setAdapter(tagAdapter);

        //默认选项为随机
        for (int i = 0; i < choose_blood_sugar.length; i++) {
            if (choose_blood_sugar[i].equals("随机")) {
                tagAdapter.setSelectedList(i);
                break;
            }
        }

        id_flowlayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                When = position;

                if (choose_blood_sugar[When].equals("自定义")) {
                    dialog();
                    wt_time.FormatTime(TimeZoneUtil.getHour(new Date()), TimeZoneUtil.getMinute(new Date()));
                } else {
                    sw_testingVal.setTitleName(choose_blood_sugar[When]);
                    if (choose_blood_sugar[When].equals("随机")) {
                        String Time = TimeZoneUtil.sdf.format(new Date());
                        wt_time.setTextVal(Time.substring(11, Time.length() - 3));
                    } else {
                        wt_time.setTextVal(choose_blood_time[When]);
                    }

                }
                return true;
            }
        });

        //隐藏日期按钮
        wd_dataAdd.hideViewDate();
        if (TimeVal != null && TimeVal.length() > 0) {
            wd_dataAdd.setTimeDate(TimeVal);
        }

        sw_testingVal.onClickTextView(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edittText(null);
            }
        });
    }


    //自定义血糖监测
    String custom = null;

    public void dialog() {
        final EditText et = new EditText(this);
        et.setHint("请填写自定义血糖标签");
//        et.setText(sw_testingVal.geTitleName());
        new AlertDialog.Builder(this).setTitle("请输入备注")
                .setView(et)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        if (et.getText().toString().trim().length() == 0 || et.getText().toString() == null) {
                            Toast.makeText(getApplicationContext(), "请填写自定义血糖", Toast.LENGTH_LONG).show();
                            return;
                        } else {
                            sw_testingVal.setTitleName(et.getText().toString());
                            custom = et.getText().toString();
                        }
                    }
                })
                .show();
    }

    @Override
    protected void initData() {
        dailyRecordPresenter = new DailyRecordPresenter(this);
        //获取显示的日期
        voidDataInit();
    }

    //初始化adapter布局
    public void initAdapter(List<TemperatureTableItem> data) {
        bloodSugarAdapter = new BloodSugarAdapter(data);
        rv_list.setAdapter(bloodSugarAdapter);

        bloodSugarAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {

                    case R.id.msgcheck:
                        if (bloodSugarAdapter.getData().get(position).getStats() != null) {
                            TemperatureTableItem temperatureTableItem = bloodSugarAdapter.getData().get(position);
                            edittText(temperatureTableItem);
                        }
                        break;
                }
            }
        });

        bloodSugarAdapter.setOnItemChildLongClickListener(new BaseQuickAdapter.OnItemChildLongClickListener() {
            @Override
            public boolean onItemChildLongClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.msgcheck:
                        if (bloodSugarAdapter.getData().get(position).getStats() != null) {
                            TemperatureTableItem temperatureTableItem = bloodSugarAdapter.getData().get(position);
                            dialogdelete(temperatureTableItem);
                        }
                        break;
                }
                return true;
            }
        });

    }


    public void dialogdelete(final TemperatureTableItem temperatureTableItem) {

        Dialog.Builder builder = new SimpleDialog.Builder(R.style.SimpleDialogLight) {
            @Override
            public void onPositiveActionClicked(DialogFragment fragment) {
                super.onPositiveActionClicked(fragment);
                dailyRecordPresenter.updateAloneItemDailyRecordDetail(temperatureTableItem.getId(), "",
                        "", "", ConstantManger.DELETEDAILY, "", "");
            }

            @Override
            public void onNegativeActionClicked(DialogFragment fragment) {
                super.onNegativeActionClicked(fragment);
            }
        };
        builder.title("确认删除检测项吗？")
                .positiveAction("确定")
                .negativeAction("取消");
        ((SimpleDialog.Builder) builder).message("检测值可以帮助医生更准确的了解你的情况");
        DialogFragment fragment = DialogFragment.newInstance(builder);

        if (this instanceof AppCompatActivity) {
            AppCompatActivity activity = this;
            fragment.show(activity.getSupportFragmentManager(), null);
        }
    }


    private final double sugarMin = 1.7;
    private final double sugarMax = 40;

    public void edittText(final TemperatureTableItem temperatureTableItem) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("请输血糖检测值");
        View views = LayoutInflater.from(this).inflate(R.layout.dialog_edit_detection, null);
        builder.setView(views);
        final EditText edit_min = (EditText) views.findViewById(R.id.edit_detection);
        edit_min.setFilters(new InputFilter[]{new InputFilter.LengthFilter(4)});
        edit_min.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                edit_min.setSelection(s.length());
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                int selectionStart = edit_min.getSelectionStart();
                int selectionEnd = edit_min.getSelectionEnd();
                if (s.toString() != null && s.toString().length() > 0) {
                    if (OutliersValues.editTextNum(s.toString())) {
                        if (!StringUtils.isOnlyPointNumber(s.toString(), 1)) {
                            s.delete(selectionStart - 1, selectionEnd);
                            edit_min.setText(s);
                            edit_min.setSelection(s.length());
                        }
                        float val = Float.parseFloat(s.toString());
                        TextColer(edit_min, OutliersValues.bloodSugar(val));
                    }
                }

                if (s.toString().trim().substring(0).equals(".")) {
                    edit_min.setText("0" + s);
                    edit_min.setSelection(2);
                }
            }
        });

        StringBuffer stringBuffer=new StringBuffer();
        if(temperatureTableItem!=null){
            stringBuffer.append("确定");
            edit_min.setText(temperatureTableItem.getLogValue() + "");
        }else{
            stringBuffer.append("提交");
        }


        builder.setPositiveButton(stringBuffer.toString(), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                String val = edit_min.getText().toString();
                String Temperature = "";
                if (val.length() != 0) {
                    double douval = Double.parseDouble(val);
                    if (douval < 1.7) {

                        msg("检测值为不可能值");
                        return;
                    }
                    if (sugarMin <= douval && douval <= sugarMax) {
                        Temperature = douval + "";
                    } else {
                        msg("检测值为不可能值");
                        edit_min.setText("");
                        return;
                    }
                } else {
                    msg("检测值为不可能值");
                    return;
                }
                if(temperatureTableItem!=null){
                    //异常值检测
                    dailyRecordPresenter.updateAloneItemDailyRecordDetail(temperatureTableItem.getId(), Temperature, "",
                            temperatureTableItem.getDailyitemName(), ConstantManger.UPDATEDAILY, abnormalVal(val), temperatureTableItem.getIndexId() + "");
                }else{
                    sw_testingVal.EditTextView(Temperature);
                    isUpdate=false;
                    action_preservation();
                }

            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                showKeyboard(edit_min);
            }
        }, 300);
        builder.show();
    }

    public void showKeyboard(EditText editText) {
        if (editText != null) {
            //设置可获得焦点
            editText.setFocusable(true);
            editText.setFocusableInTouchMode(true);
            //请求获得焦点
            editText.requestFocus();
            //调用系统输入法
            InputMethodManager inputManager = (InputMethodManager) editText
                    .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.showSoftInput(editText, 0);
        }
    }

    public void TextColer(EditText textView, int color) {
        if (color == 0) {
            textView.setTextColor(color(R.color.btcolor));
        } else {
            textView.setTextColor(color(R.color.red));
        }
    }

    private int color(int value) {
        return MainAppliaction.getInstance().getResources().getColor(value);
    }


    @Override
    public void onDailyRecordDetailsSuccess(AnotherResult<DailyRecordDetailsData> data) {
        List<TemperatureTableItem> temperatureTableItemList = new ArrayList<>();
        if (data.getList().size() != 0) {
            TemperatureTableItem tableItem = new TemperatureTableItem();
            tableItem.setDailyitemName("状态");
            tableItem.setItemType(TemperatureTableItem.HEAD);
            tableItem.setDailyitemDose("毫摩尔/升(mmol/L)");
            temperatureTableItemList.add(tableItem);
        }
        for (int i = 0; i < data.getList().size(); i++) {
            TemperatureTableItem temperatureTableItem = new TemperatureTableItem();
            temperatureTableItem.setId(data.getList().get(i).getId() + "");
            temperatureTableItem.setLogTime(data.getList().get(i).getLogTime().substring(5, 16));
            temperatureTableItem.setLogValue(data.getList().get(i).getLogValue());
            temperatureTableItem.setDailyitemDose(data.getList().get(i).getDailyitemDose());
            if (data.getList().get(i).getMarkValue() == null || data.getList().get(i).getMarkValue().length() == 0) {
                temperatureTableItem.setDailyitemName(data.getList().get(i).getDailyitemName());//data.getList().get(i).getDailyitemName()
            } else {
                temperatureTableItem.setDailyitemName(data.getList().get(i).getMarkValue());//data.getList().get(i).getDailyitemName()
            }
            temperatureTableItem.setIndexId(data.getList().get(i).getIndexId());
            temperatureTableItem.setItemType(TemperatureTableItem.BODY);
            temperatureTableItem.setReferenceValue(ConstantManger.BILLDSUGARFERENCE);//参考值

            temperatureTableItem.setStats(OutliersValues.bloodSugar(Float.parseFloat(data.getList().get(i).getLogValue())) + "");
            temperatureTableItemList.add(temperatureTableItem);
        }
        initAdapter(temperatureTableItemList);
        int[] index = {0, 6};
        lc_post_list.setFlashback(temperatureTableItemList, index);
        dessDialog();
    }

    //保存
    boolean isUpdate=true;
    @OptionsItem(R.id.action_preservation)
    public void action_preservation() {

        if(isUpdate){
            if(!sw_testingVal.updateVal()){
                msg("请修改检测值");
                return;
            }
        }

        //检测值
        final String testVal = sw_testingVal.getDetectVal();
        //获取显示的日期
        String Time = wt_time.getTime();
        String Date = wd_dataAdd.getDataTime();//检测日期

        final StringBuffer stringBuffer = new StringBuffer();

        if (choose_blood_sugar.length == 0) {
            msg("本地文件出现问题");
            return;
        }

        if (When == -1) {
            When = 9;//没有选择血糖标签时默认为随机
        }
        stringBuffer.append(Date);
        stringBuffer.append(" " + Time + ":00");


        String TestingName = null;
        if (choose_blood_sugar[When].equals("自定义")) {
            if (custom == null) {
                msg("请重新填写自定义血糖标签");
                dialog();
                return;
            }
            TestingName = custom;
        } else {
            TestingName = choose_blood_sugar[When];
        }
        final String finalTestingName = TestingName;
        isUpdate=true;
        dailyRecordPresenter.AddDailyRecordDetailData(
                testVal,
                stringBuffer.toString(),
                finalTestingName,
                "",
                ConstantManger.BILLDSUGAR,
                ConstantManger.BILLDSUGARDOSE, abnormalVal(testVal));
    }

    //异常值检测
    public String abnormalVal(String val) {
        String warn = "";
        int stats = OutliersValues.bloodSugar(Float.parseFloat(val));
        if (stats == 0) {
            warn = "0";
        } else {
            warn = "1";
        }

        return warn;
    }

    @Override
    public void onError(String msg) {
        if (msg != null) {
            msg(msg);
        }
        dessDialog();
    }

    @Override
    public void onRefreshUI() {
        dessDialog();
    }

    @Override
    public void onSubmitSuccess(DataStateResult dataStateResult) {
        if (dataStateResult.getMsgCode().equals("0x00000000")) {
            msg("操作成功");
            custom = null;
            //获取显示的日期
            voidDataInit();
            sw_testingVal.defaultVal("50");
        }
        dessDialog();
    }

    @Override
    public void onUpdateValueSuccess(DataStateResult dataStateResult) {

        if (dataStateResult.getMsgCode().equals("0x00000000")) {
            voidDataInit();
        }
    }

    @Override
    public void onDeleteValueSuccess(DataStateResult dataStateResult) {
        if (dataStateResult.getMsgCode().equals("0x00000000")) {
            voidDataInit();
        }
    }

    public void voidDataInit() {
        //获取显示的日期
        final String type = "7";
        String Time = wd_dataAdd.getDataTime();
        dailyRecordPresenter.GetUserOneDayDailyRecordData(ConstantManger.BILLDSUGAR, Time, type);
    }
}
